package com.wkbb.basic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wkbb.basic.constant.BasicConstants;
import com.wkbb.basic.feign.WxFeignService;
import com.wkbb.basic.mapper.*;
import com.wkbb.basic.model.*;
import com.wkbb.basic.service.*;
import com.wkbb.basic.vo.SysUserRoleTypeVo;
import com.wkbb.common.base.BaseServiceImpl;
import com.wkbb.common.config.ServiceConfig;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.dto.basic.*;
import com.wkbb.common.enums.*;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.BeanUtil;
import com.wkbb.common.utils.NewMD5Util;
import com.wkbb.common.utils.StringUtil;
import com.wkbb.common.utils.ThreadPoolUtil;
//import com.wkbb.common.vo.DeviceUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserUnionMapper userUnionMapper;

    @Autowired
    private UserOpenMapper userOpenMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ClassInfoMapper classInfoMapper;

    @Autowired
    private UserVisitorMapper visitorMapper;

    @Autowired
    private FamilyMapper familyMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;

    @Autowired
    private UserLastLoginMapper userLastLoginMapper;

    @Autowired
    private UserOpenService userOpenService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private ServiceConfig serviceConfig;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private WxFeignService wxFeignService;

    @Autowired
    private UserSmartMapper userSmartMapper;

    @Autowired
    private TeacherManageService teacherManageService;

    @Autowired
    private YouTuService youTuService;

    @Autowired
    private WebankService webankService;

    @Autowired
    public void setMapper(UserMapper mapper) {
        super.setMapper(userMapper);
    }

    @Override
    public void insert(Long orgId, User user, int roleType, String sex,Short userType,String smartWxUserId,Boolean isSmartSubscribe) {
        if (null == user.getHeadImgUrl()) {
            if (null != sex) {
                if (sex.equals(SexTypeEnum.MAN.getDesc())) {
                    if (RoleTypeEnum.FAMILY.getValue() == roleType) {
                        user.setHeadImgUrl(serviceConfig.getFamilyManPicUrl());
                    } else {
                        user.setHeadImgUrl(serviceConfig.getTeacherManPicUrl());
                    }
                } else {
                    if (RoleTypeEnum.FAMILY.getValue() == roleType) {
                        user.setHeadImgUrl(serviceConfig.getFamilyWoManPicUrl());
                    } else {
                        user.setHeadImgUrl(serviceConfig.getTeacherWoManPicUrl());
                    }
                }
            }
        }

        userMapper.insert(user);
        updateUserInfo(orgId, user.getId());
        log.info("******UserServiceImpl*******userSmart:{}", smartWxUserId);
        //新增或者更新userSmart
        repairUserSmart(orgId, user.getId(),smartWxUserId,isSmartSubscribe,roleType);

    }

    @Override
    public void repairUserSmart(Long orgId, Long userId,String smartWxUserId,Boolean isSmartSubscribe,Integer roleType) {
        if(!StringUtil.isEmptyIgnoreBlank(smartWxUserId)){
            UserSmart userSmart = getUserSmart(orgId, userId, roleType);

            if(null==userSmart){
                userSmart= new UserSmart();
                userSmart.setOrgId(orgId);
                userSmart.setRoleType(roleType);
                userSmart.setSmartWxUserId(smartWxUserId);
                userSmart.setUserId(userId);
                userSmart.setIsSmartSubscribe(isSmartSubscribe==null?false:isSmartSubscribe);

                userSmartMapper.insert(userSmart);
            }else{
                userSmart.setSmartWxUserId(smartWxUserId);
                if(null!=isSmartSubscribe){
                    userSmart.setIsSmartSubscribe(isSmartSubscribe);
                }
                userSmartMapper.update(userSmart);
            }

        }
    }

    @Override
    public void update(Long orgId, User user, int roleType, boolean isBack,String userSmartId,Boolean isSmartSubscribe) throws Exception {
        if (isBack) {
            userMapper.updateBack(user);
        } else {
            update(user);
        }

        updateRedisTemplate(orgId, user.getId(), roleType, user.getRoleType());

        //修改用户的userSmart
        repairUserSmart(orgId,user.getId(),userSmartId,isSmartSubscribe,roleType);
    }

//    @Override
//    public List<DeviceUserVo> getUserByDeviceOrg(Long orgId, Long userId, String roleType, Date date) {
//        Map<String, Object> params = new HashMap<>(Constants.INIT_MAP_SIZE_5);
//        params.put("orgId", orgId);
//        params.put("userId", userId);
//        params.put("roleType", roleType);
//        params.put("updateTime", date);
//        List<DeviceUserVo> userVoList = userMapper.getUserByDeviceOrg(params);
//        if(!CollectionUtils.isEmpty(userVoList)){
//            userVoList.forEach(e->{
//                String cardNo = StringUtils.isEmpty(e.getCardNo()) ? null : e.getCardNo().toString();
//                if(!StringUtils.isEmpty(cardNo)){
//                    e.setCardNo(cardNo.endsWith(",") ? cardNo.substring(0,cardNo.length()-1) : cardNo);
//                }
//            });
//        }
//        return userVoList;
//    }

    @Override
    public EmployeeInfoDto getEmloyeeByPwd(String account, String password) {
        return employeeMapper.getEmloyeeByPwd(account,password);
    }

    @Override
    public List<RoleTypeJsonDto> updateRoleTypeJson(Object roleTypeJson, Short oldRoleType, Short roleType, Long oldOrgId, Long orgId,Long userId) {
        List<RoleTypeJsonDto> roleTypeJsons = JSONObject.parseArray(JSON.toJSONString(roleTypeJson), RoleTypeJsonDto.class);
        //如果原来没有角色
        if (roleTypeJsons == null || roleTypeJsons.isEmpty()) {
            //如果是新增角色，直接新增
            if (roleType != null && orgId != null) {
                return addNewRole(roleTypeJsons, roleType, orgId);
            }
            return null;
        } else if (roleTypeJsons.size() == 1) {
            RoleTypeJsonDto roleTypeJsonDto = roleTypeJsons.get(0);
            if (roleTypeJsonDto != null && roleTypeJsonDto.getRoleTypes() != null && !roleTypeJsonDto.getRoleTypes().isEmpty()) {
                if (RoleTypeEnum.TOURIST.getValue() == roleTypeJsonDto.getRoleTypes().get(0).getRoleType()) {
                    deleteOldRoleType(null, (short) RoleTypeEnum.TOURIST.getValue(), roleTypeJsons,userId);
                }
            }
        }

        if (null != oldRoleType) {
            //刪除老的权限
            deleteOldRoleType(oldOrgId, oldRoleType, roleTypeJsons,userId);

            //如果没有要新增的角色
            if (roleType == null) {
                //检查是否已经变成游客
                return checkIsNeedAddVisitor(roleTypeJsons);
            }
        }

        //没有新增的身份，直接退出
        if (roleType == null) {
            return roleTypeJsons;
        }

        //是否在roleType里已有当前学校
        boolean orgIdFlag = checkRoleOrgExists(roleTypeJsons, orgId);
        //是否在roleType相应学校里已有角色
        boolean roleTypeFlag = checkRoleTypeExists(orgIdFlag, roleTypeJsons, orgId, roleType);

        //如果原角色信息里有该学校
        if (orgIdFlag) {
            //原角色信息里有该角色
            if (roleTypeFlag) {
                //直接返回这个角色信息
                return roleTypeJsons;
            } else {
                //在角色信息中的指定学校内新增角色
                return addRole(roleTypeJsons, orgId, roleType);
            }
        } else {
            //在角色信息中新增该学校并在内添加角色
            return addNewRole(roleTypeJsons, roleType, orgId);
        }
    }

    /**
     * 在已有学校里加入角色
     */
    private List<RoleTypeJsonDto> addRole(List<RoleTypeJsonDto> roleTypeJsons, Long orgId, Short roleType) {
        for (RoleTypeJsonDto roleTypelist : roleTypeJsons) {
            if (roleTypelist.getOrgId().equals(orgId)) {
                RoleTypeDto roleTypeDto = new RoleTypeDto();
                roleTypeDto.setRoleType(roleType);
                roleTypeDto.setRoleTypeName(RoleTypeEnum.getDesc(roleType.intValue()));
                roleTypelist.getRoleTypes().add(roleTypeDto);
                return roleTypeJsons;
            }
        }
        return roleTypeJsons;
    }

    /**
     * 是否在roleType相应学校里已有角色
     */
    private Boolean checkRoleTypeExists(Boolean orgIdFlag, List<RoleTypeJsonDto> roleTypeJsons, Long orgId, Short roleType) {
        if (roleTypeJsons.isEmpty()) {
            return false;
        }

        if (orgIdFlag) {
            for (RoleTypeJsonDto roleTypelist : roleTypeJsons) {
                if (roleTypelist.getOrgId().equals(orgId)) {
                    List<RoleTypeDto> userTypes = roleTypelist.getRoleTypes();
                    for (RoleTypeDto userTy : userTypes) {
                        if (userTy.getRoleType().equals(roleType)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 是否在roleType里已有当前学校
     */
    private Boolean checkRoleOrgExists(List<RoleTypeJsonDto> roleTypeJsons, Long orgId) {
        if (roleTypeJsons.isEmpty()) {
            return false;
        }

        for (RoleTypeJsonDto roleTypelist : roleTypeJsons) {
            if (roleTypelist.getOrgId().equals(orgId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查是否已经变成游客
     */
    private List<RoleTypeJsonDto> checkIsNeedAddVisitor(List<RoleTypeJsonDto> roleTypeJsons) {
        if (roleTypeJsons != null && !roleTypeJsons.isEmpty()) {
            return roleTypeJsons;
        }

        //添加游客身份
        return addNewRole(roleTypeJsons, (short) RoleTypeEnum.TOURIST.getValue(), null);
    }

    /**
     * 新增用户角色
     *
     * @param roleTypeJsons 原来的用户角色列表
     * @param roleType      用户新角色
     * @param orgId         组织ID
     */
    private List<RoleTypeJsonDto> addNewRole(List<RoleTypeJsonDto> roleTypeJsons, Short roleType, Long orgId) {
        if (roleType == null) {
            return null;
        }

        //包装组织ID等信息
        RoleTypeJsonDto roleTypeJsonDto = new RoleTypeJsonDto();
        roleTypeJsonDto.setOrgId(orgId);

        //新增的用户角色
        RoleTypeDto roleTypeDto = new RoleTypeDto();
        roleTypeDto.setRoleType(roleType);
        roleTypeDto.setRoleTypeName(RoleTypeEnum.getDesc(roleType.intValue()));

        //roleTypes列表信息
        List<RoleTypeDto> roleTypeDtoList = new ArrayList<>();
        roleTypeDtoList.add(roleTypeDto);
        roleTypeJsonDto.setRoleTypes(roleTypeDtoList);

        //最外层再用列表包装
        if (roleTypeJsons == null) {
            roleTypeJsons = new ArrayList<>();
        }
        roleTypeJsons.add(roleTypeJsonDto);
        return roleTypeJsons;
    }

    /**
     * 删除旧角色
     *
     * @param oldOrgId      旧学校ID
     * @param oldRoleType   旧角色
     * @param roleTypeJsons 当前角色jason
     */
    private void deleteOldRoleType(Long oldOrgId, Short oldRoleType, List<RoleTypeJsonDto> roleTypeJsons,Long userId) {
        //如果是删除游客角色，直接清空
        if (RoleTypeEnum.TOURIST.getValue() == oldRoleType) {
            roleTypeJsons.clear();
            return;
        }

        if (oldOrgId == null) {
            return;
        }

        boolean deleteRoleType = false;
        for (RoleTypeJsonDto roleTypelist : roleTypeJsons) {
            if (roleTypelist.getOrgId().equals(oldOrgId)) {
                List<RoleTypeDto> roleTypes = roleTypelist.getRoleTypes();
                for (RoleTypeDto newRoleType : roleTypes) {
                    if (newRoleType.getRoleType().equals(oldRoleType)) {
                        if (roleTypes.size() > 1) {
                            roleTypes.remove(newRoleType);
                        } else {
                            roleTypeJsons.remove(roleTypelist);

                            //通过userCode获取个体是否创建
                            YoutuPerson youtuPerson = youTuService.getYoutuPerson(oldOrgId, userId);

                            if(null!=youtuPerson){

                                try{

                                    log.info("---------删除当前用户人脸----------userId:{},orgId:{}",userId,oldOrgId);
                                    //删除用户学校身份删除人脸
                                    ThreadPoolUtil.addTask(() ->webankService.modifyFace(youtuPerson.getPersonId(), oldOrgId,true,null,null,null));
                                }catch (Exception e){
                                    log.error("---------删除当前用户人脸异常----------e:{}",e);
                                }
                            }
                        }
                        deleteRoleType = true;
                        break;
                    }
                }
            }
            if (deleteRoleType) {
                break;
            }
        }
    }

    @Override
    public void updateRedisTemplate(Long orgId, Long userId, Integer roleType, Object roleTypeObject) {
        //更新用户信息缓存
        updateUserInfo(orgId, userId);
        //更新昵称信息缓存
        updateNickName(orgId, userId, roleType);
    }

    private void updateNickName(Long orgId, Long userId, Integer roleType) {
        //如果是学生身份，删除其对应家长的缓存，区分学校
        if (roleType == RoleTypeEnum.STUDENT.getValue()) {
            Map<String, Object> familyParams = new HashMap<String, Object>(2);
            familyParams.put("orgId", orgId);
            familyParams.put("studentId", userId);
            //查询家长
            List<FamilyInfoDto> familyInfoDtoList = familyMapper.getFamilyInfoList(familyParams);
            if (familyInfoDtoList == null || familyInfoDtoList.isEmpty()) {
                return;
            }
            familyInfoDtoList.forEach(familyInfoDto -> userOpenService.clearNickName( familyInfoDto.getUserId()));
        } else {
            //如果是家长或老师身份，删除其所有缓存,不分学校
            userOpenService.clearNickName(userId);
        }
    }

    @Override
    public void updateUserInfo(Long orgId, Long userId) {
        log.info("*******updateUserInfo******orgId:{},userId:{}", orgId, userId);
        UserDto userDto = null;

       /* ResultDTO<AccountDto> result = wxFeignService.getAccountByOrg(orgId);
        if (result.isSuccess()) {
            AccountDto accountDto = result.getData();
            if (null != accountDto) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("userId", userId);
                params.put("accountId", accountDto.getId());

                UserUnion userUnion = userUnionMapper.getByMapParams(params);
                if (null != userUnion && null != userUnion.getUnionId()) {
                    userDto = this.getUserInfo(false,userUnion.getAccountId(), orgId, userId);
                    userDto.setUnionId(userUnion.getUnionId());//设置UnionId
                }

                if (null != userDto) {
                    //设置新键
                    String userTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_FRONT + RedisKeyConstant.WKBB_BASIC_USER_FRONT_ACCOUNT_UNIONID, userUnion.getAccountId(), userUnion.getUnionId());
                    redisTemplateUtil.set(userTokenRedisKey, userDto, RedisKeyConstant.EXPIRATION_TIME_1_YEAR);

                    //路由用户
                    String userRouteTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_ROUTE + RedisKeyConstant.WKBB_BASIC_USER_ROUTE_TOKEN_UNIONID, userUnion.getUnionId());
                    String userRouteTokenStr = redisTemplateUtil.getJSON(userRouteTokenRedisKey);
                    if (!StringUtil.isEmpty(userRouteTokenStr)) {
                        redisTemplateUtil.set(userRouteTokenRedisKey, userDto, RedisKeyConstant.EXPIRATION_TIME_1_YEAR);
                    }
                }
            }
        }*/

    }

    @Override
    @Transactional
    public void deleteUserInfo(Long orgId, Long userId, Integer roleType) throws Exception {
        //先删除user表角色信息，再更新缓存
        User user = userMapper.getByPrimaryKey(userId);
        if(null!=user) {
            Object roleTypeObj = this.updateRoleTypeJson(user.getRoleType(), roleType.shortValue(), null, orgId, null, userId);
            user.setId(userId);
            user.setRoleType(roleTypeObj);
            this.update(user);
           // this.deleteRedisWkbbBasicUserBack(orgId, userId);

            //删除用户和智慧校园表关联
            UserSmart userSmart = getUserSmart(orgId, userId, roleType);

            if(null!=userSmart){
                userSmartMapper.deleteByPrimaryKey(userSmart.getId());
            }
        }
    }

    @Override
    public UserSmart getUserSmart(Long orgId, Long userId, Integer roleType) {
        Map<String, Object> userParams = new HashMap<String, Object>();
        userParams.put("orgId",orgId);
        userParams.put("userId",userId);
        userParams.put("roleType",roleType);
        return userSmartMapper.getByMapParams(userParams);
    }

    @Override
    public User getUserByMobile(String mobile) {
        Map<String, Object> userParams = new HashMap<String, Object>();
        userParams.put("mobile", mobile);

        return userMapper.getByMapParams(userParams);
    }

    @Override
    public UserInfoDto getUserInfoByMobile(String mobile) {
        Map<String, Object> userParams = new HashMap<String, Object>();
        userParams.put("mobile", mobile);
        userParams.put("isFamily", 1);
        return userMapper.getUserInfoByMobile(userParams);
    }


    /**
     * 查询用户详情信息
     *
     * @param params userId
     * @return 用户详情
     */
    @Override
    public UserInfoDto getUserInfoById(Map<String, Object> params) {
        return userMapper.getUserInfoByMobile(params);
    }

    @Override
    public int checkMobile(String mobile, Long userId) {
        if (!StringUtil.isNullOrBlank(mobile)) {
            User user = getUserByMobile(mobile);
            //如果没有用户占用手机号，直接可用
            if (user == null) {
                return BasicConstants.MOBILE_AVAILABLE;
            }

            //有用户ID情况，相当于修改
            if (userId != null && userId != 0) {
                //判断手机号所属用户与当前用户是否一致
                //不一致返回手机号被占用
                if (user.getId() != userId.longValue()) {
                    return BasicConstants.MOBILE_HAS_REGISTER;
                }
            } else {
                return BasicConstants.MOBILE_HAS_REGISTER;
            }
        }
        return BasicConstants.MOBILE_AVAILABLE;
    }

    @Override
    public ErrorCode checkMobileErrorCode(String mobile, String cardNo, String jobNo, Long userId, Integer roleType, Long orgId,Long classId) {
        return checkMobileErrorCode(mobile, cardNo, jobNo, userId, roleType, orgId, null,classId);
    }

    @Override
    public ErrorCode checkMobileErrorCode(String mobile, String cardNo, String jobNo, Long userId, Integer roleType, Long orgId, String account,Long classId) {
        int result;

        if (!StringUtil.isNullOrBlank(mobile)) {
            result = checkMobile(mobile, userId);
            if (result == BasicConstants.MOBILE_HAS_REGISTER) {
                return ErrorCode.USER_REGISTER_PHONE_EXIST;
            } else if (result == BasicConstants.USER_NOT_EXIST) {
                return ErrorCode.USER_NOT_EXIST;
            } else if (roleType == null) {
                return null;
            }
        }

        if (!StringUtil.isNullOrBlank(cardNo)) {
            result = checkCardNo(cardNo, userId, roleType, orgId);
            if (result == BasicConstants.CARDNO_HAS_REGISTER) {
                return ErrorCode.CARDNO_HAS_REGISTER;
            }
        }

        if (!StringUtil.isNullOrBlank(jobNo)) {
            result = checkJobNo(jobNo, userId, roleType, orgId,classId);
            if (result == BasicConstants.JOBNO_HAS_REGISTER) {
                if (RoleTypeEnum.TEACHER.getValue() == roleType) {
                    return ErrorCode.JOBNO_HAS_REGISTER;
                } else {
                    return ErrorCode.STUDENTNO_HAS_REGISTER;
                }
            }
        }

        if (!StringUtil.isNullOrBlank(account)) {
            result = checkAccount(account, userId, orgId);
            if (result == BasicConstants.ACCOUNT_HAS_REGISTER) {
                return ErrorCode.ACCOUNT_HAS_REGISTER;
            }
        }

        return null;
    }

    private int checkAccount(String account, Long userId, Long orgId) {
        Map<String, Object> params = new HashMap<>();
        params.put("account", account);

        List<Employee> employeeList = employeeMapper.getListByMapParams(params);
        if (employeeList != null && !employeeList.isEmpty()) {
            if (userId != null) {
                for (Employee employee : employeeList) {
                    if (employee.getUserId() != userId.longValue()) {
                        return BasicConstants.ACCOUNT_HAS_REGISTER;
                    }
                }
            } else {
                return BasicConstants.ACCOUNT_HAS_REGISTER;
            }
        }

        return BasicConstants.MOBILE_AVAILABLE;
    }

    @Override
    public int checkJobNo(String jobNo, Long userId, Integer roleType, Long orgId,Long classId) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("orgId", orgId);
        if (RoleTypeEnum.TEACHER.getValue() == roleType) {
            params.put("jobNo", jobNo);
            List<Employee> employeeList = employeeMapper.getListByMapParams(params);
            if (employeeList != null && !employeeList.isEmpty()) {
                if (userId != null) {
                    for (Employee employee : employeeList) {
                        if (employee.getUserId() != userId.longValue()) {
                            return BasicConstants.JOBNO_HAS_REGISTER;
                        }
                    }
                } else {
                    return BasicConstants.JOBNO_HAS_REGISTER;
                }
            }
        } else if (RoleTypeEnum.STUDENT.getValue() == roleType) {
            params.put("studentNo", jobNo);
            params.put("classId", classId);
            params.put("userId", userId);
            Student stu = studentMapper.findStudent(params);
            if (stu != null){
                return BasicConstants.JOBNO_HAS_REGISTER;
            }
//            List<Student> studentList = studentMapper.getListByMapParams(params);
//            if (studentList != null && !studentList.isEmpty()) {
//                if (userId != null) {
//                    for (Student student : studentList) {
//                        if (student.getUserId() != userId.longValue()) {
//                            return BasicConstants.JOBNO_HAS_REGISTER;
//                        }
//                    }
//                } else {
//                    return BasicConstants.JOBNO_HAS_REGISTER;
//                }
//            }
        }
        return BasicConstants.MOBILE_AVAILABLE;
    }

    private int checkCardNo(String cardNo, Long userId, Integer roleType, Long orgId) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("orgId", orgId);
        params.put("cardNo", cardNo);

        if (RoleTypeEnum.TEACHER.getValue() == roleType) {
            List<Employee> employeeList = employeeMapper.getListByMapParams(params);
            if (employeeList != null && !employeeList.isEmpty()) {
                if (userId != null) {
                    for (Employee employee : employeeList) {
                        if (employee.getUserId() != userId.longValue()) {
                            return BasicConstants.CARDNO_HAS_REGISTER;
                        }
                    }
                } else {
                    return BasicConstants.CARDNO_HAS_REGISTER;
                }
            }
        } else if (RoleTypeEnum.FAMILY.getValue() == roleType) {
            List<Family> familyList = familyMapper.getListByMapParams(params);
            if (familyList != null && !familyList.isEmpty()) {
                if (userId != null) {
                    for (Family family : familyList) {
                        if (family.getUserId() != userId.longValue()) {
                            return BasicConstants.CARDNO_HAS_REGISTER;
                        }
                    }
                } else {
                    return BasicConstants.CARDNO_HAS_REGISTER;
                }
            }
        } else if (RoleTypeEnum.STUDENT.getValue() == roleType) {
            List<Student> studentList = studentMapper.getListByMapParams(params);
            if (studentList != null && !studentList.isEmpty()) {
                if (userId != null) {
                    for (Student student : studentList) {
                        if (student.getUserId() != userId.longValue()) {
                            return BasicConstants.CARDNO_HAS_REGISTER;
                        }
                    }
                } else {
                    return BasicConstants.CARDNO_HAS_REGISTER;
                }
            }
        }
        return BasicConstants.MOBILE_AVAILABLE;
    }

    @Override
    public List<UserDto> loginByPwd(String account, String password) {

        List<UserDto> userList = new ArrayList<UserDto>();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("account", account);
        params.put("password", password);


        List<Employee> employeeInfoList = employeeMapper.getListByMapParams(params);

        if (employeeInfoList.size() > 0) {

            //取一个用户即可
            //查询用户个人信息
            Employee employeeInfo = employeeInfoList.get(0);
            UserDto userDto = getUserInfoManage(null, employeeInfo.getOrgId(), employeeInfo.getUserId(), true);
            log.info("json:"+ JsonUtil.objectToJson(userDto));
            userList.add(userDto);
        }

        return userList;
    }

    /**
     * 后台取用户登录数据
     */
    @Override
    public UserDto getUserInfoManage(Long accountId, Long orgId, Long userId, Boolean isAll) {
        UserDto userDto = new UserDto();

        //查询用户个人信息
        UserInfoDto userInfoDto = this.getUserInfoByUser(orgId, userId, RoleTypeEnum.TEACHER.getValue());
        log.info("*****getUserInfoManage userInfoDto:{}****",userInfoDto);
        BeanUtils.copyProperties(userInfoDto, userDto);

        //获取组织角色信息
        ArrayList<RoleTypeJsonDto> roleTypeJsonsList = new ArrayList<RoleTypeJsonDto>();

        //查询用户所在组织的角色
        Map<String, Object> roleTypeParams = new HashMap<String, Object>();
        if (!isAll) {
            roleTypeParams.put("orgId", orgId);
        }
        roleTypeParams.put("userId", userId);
        List<SysUserRoleTypeVo> sysUserRoleTypeVoList = sysRoleService.getUserRoleTypeList(roleTypeParams);
        for (SysUserRoleTypeVo sysUserRoleTypeVo : sysUserRoleTypeVoList) {
            String sysUserRoleType = sysUserRoleTypeVo.getRoleType();
            String[] userRoleTypeArr = sysUserRoleType.split(",");

            ArrayList<RoleTypeDto> roleTypeList = new ArrayList<RoleTypeDto>();
            for (String userRoleType : userRoleTypeArr) {
                if (Integer.parseInt(userRoleType) == SysRoleTypeEnum.SUPER_ADMIN.getValue()) {
                    RoleTypeDto roleTypeDto = new RoleTypeDto();
                    roleTypeDto.setRoleType((short) SysRoleTypeEnum.SUPER_ADMIN.getValue());//超管
                    roleTypeDto.setRoleTypeName(SysRoleTypeEnum.SUPER_ADMIN.getDesc());
                    roleTypeList.add(roleTypeDto);
                } else if (Integer.parseInt(userRoleType) == SysRoleTypeEnum.ADMIN.getValue()) {
                    RoleTypeDto roleTypeDto = new RoleTypeDto();
                    roleTypeDto.setRoleType((short) SysRoleTypeEnum.ADMIN.getValue());//管理员
                    roleTypeDto.setRoleTypeName(SysRoleTypeEnum.ADMIN.getDesc());
                    roleTypeList.add(roleTypeDto);
                } else if (Integer.parseInt(userRoleType) == SysRoleTypeEnum.EMPLOYEE.getValue()) {
                    RoleTypeDto roleTypeDto = new RoleTypeDto();
                    roleTypeDto.setRoleType((short) SysRoleTypeEnum.EMPLOYEE.getValue());//职员
                    roleTypeDto.setRoleTypeName(SysRoleTypeEnum.EMPLOYEE.getDesc());
                    roleTypeList.add(roleTypeDto);
                }
            }

            //组装角色数据
            RoleTypeJsonDto roleTypeJsonDto = new RoleTypeJsonDto();

            //查询账户
//            ResultDTO<AccountDto> result = wxFeignService.getAccountByOrg(sysUserRoleTypeVo.getOrgId());
//            if (result.isSuccess()) {
//                AccountDto accountDto = result.getData();
//                if (null != accountDto) {
//                    roleTypeJsonDto.setAccountId(accountDto.getId());
//                }
//            }
            roleTypeJsonDto.setOrgId(sysUserRoleTypeVo.getOrgId());//组织ID
            roleTypeJsonDto.setOrgName(sysUserRoleTypeVo.getOrgName());//组织名称
            roleTypeJsonDto.setOrgType(sysUserRoleTypeVo.getOrgType());//组织类型
            roleTypeJsonDto.setRoleTypes(roleTypeList);

            roleTypeJsonsList.add(roleTypeJsonDto);

        }

        userDto.setRoleType(roleTypeJsonsList);

        return userDto;
    }

    /**
     * 根据用户ID获取用户信息
     */
    @Override
    public UserDto getUserInfo(Boolean routeFlag, Long accountId, Long orgId, Long userId) {

        log.info("***********getUserInfo*********routeFlag:{} accountId:{} orgId:{} userId:{}",routeFlag,accountId,orgId,userId);
        User user = userMapper.getByPrimaryKey(userId);

        UserDto userInfo = new UserDto();
        userInfo.setId(user.getId());
        userInfo.setName(user.getName());
        userInfo.setNickName(user.getNickName());
        userInfo.setHeadImgUrl(user.getHeadImgUrl());
        userInfo.setMobile(user.getMobile());
        userInfo.setUserCode(user.getUserCode());//用户编号

        //解析用户角色
        Boolean isVisitor = true;
        String roleTypeJsonStr = JSON.toJSONString(user.getRoleType());

        log.debug("*************getUserInfo****************roleTypeJsonStr:{}", roleTypeJsonStr);
        List<RoleTypeJsonDto> roleTypeDtoList = new ArrayList<>();
        List<RoleTypeJsonDto> roleTypeJsonDtoList = JSONObject.parseArray(roleTypeJsonStr, RoleTypeJsonDto.class);
        for (RoleTypeJsonDto roleTypeJsonDto : roleTypeJsonDtoList) {
            List<RoleTypeDto> roleTypes = roleTypeJsonDto.getRoleTypes();
            boolean existEmployee = false;
            List<RoleTypeDto> newRoleTypes = new ArrayList<>();
            Long roleOrgId = roleTypeJsonDto.getOrgId();
            if (null != roleTypeJsonDto.getOrgId()) {
                for (RoleTypeDto roleTypeDto : roleTypes) {
                    Integer roleType = roleTypeDto.getRoleType().intValue();
                    //前端用户不返回职员身份
                    if(roleType==RoleTypeEnum.EMPLOYEE.getValue()) {
                        existEmployee = true;
                    }
                    else {
                        //查询用户信息(取一个身份)
                        if (roleTypes.size() > 1) {
                            //默认取一个教师身份信息
                            if (roleType == RoleTypeEnum.TEACHER.getValue()) {
                                UserInfoDto userInfoDto = this.getUserInfoByUser(roleOrgId, user.getId(), roleType);
                                if (null != userInfoDto) {
                                    BeanUtils.copyProperties(userInfoDto, userInfo);

                                    roleTypeJsonDto.setCasterClassId(userInfoDto.getClassId());
                                    roleTypeJsonDto.setUserType(userInfoDto.getUserType());
                                }
                            }
                        } else {
                            UserInfoDto userInfoDto = this.getUserInfoByUser(roleOrgId, user.getId(), roleType);
                            if (null != userInfoDto) {
                                BeanUtils.copyProperties(userInfoDto, userInfo);

                                //老师则设置职位信息
                                if (roleType == RoleTypeEnum.TEACHER.getValue()) {
                                    roleTypeJsonDto.setCasterClassId(userInfoDto.getClassId());
                                    roleTypeJsonDto.setUserType(userInfoDto.getUserType());
                                }
                            }
                        }
                        newRoleTypes.add(roleTypeDto);
                    }
                }

                //覆盖新的角色，踢除职员身份
                if(existEmployee)
                {
                    roleTypeJsonDto.setRoleTypes(newRoleTypes);
                }

                //获取组织名称
                Organization organization = organizationMapper.getByPrimaryKey(roleOrgId);
                if(null!=organization) {
                    roleTypeJsonDto.setOrgType(organization.getOrgType());//组织类型
                    roleTypeJsonDto.setOrgName(organization.getName());//组织名称
                }


            }
            //有角色身份才返回
            if(roleTypeJsonDto.getRoleTypes().size()>0) {
                roleTypeDtoList.add(roleTypeJsonDto);
            }
        }
        if(roleTypeDtoList.size()>0) {
            isVisitor = false;//设置标识非游客
        }
        userInfo.setRoleType(roleTypeDtoList);

        //如果没取到真实用户信息，则取游客数据
        if (isVisitor) {
            //查询游客用户信息
            UserInfoDto userInfoDto = this.getUserInfoByUser(orgId, user.getId(), RoleTypeEnum.TOURIST.getValue());

            //设置游客信息
            ArrayList<RoleTypeJsonDto> roleTypeJsonsList = new ArrayList<RoleTypeJsonDto>();
            ArrayList<RoleTypeDto> roleTypeList = new ArrayList<RoleTypeDto>();

            RoleTypeDto roleTypeDto = new RoleTypeDto();
            roleTypeDto.setRoleType((short) RoleTypeEnum.TOURIST.getValue());//游客
            roleTypeDto.setRoleTypeName(RoleTypeEnum.TOURIST.getDesc());
            roleTypeList.add(roleTypeDto);

            RoleTypeJsonDto roleTypeJsonDto = new RoleTypeJsonDto();
            roleTypeJsonDto.setOrgId(null);
            roleTypeJsonDto.setRoleTypes(roleTypeList);

            roleTypeJsonsList.add(roleTypeJsonDto);

            userInfo.setRoleType(roleTypeJsonsList);

            if (null != userInfoDto) {
                userInfo.setSex(userInfoDto.getSex());
            }
        }

        userInfo.setMobile(user.getMobile());//防止被覆盖掉
        userInfo.setAccountId(accountId);

        return userInfo;
    }

    /**
     * 根据用户ID获取用户信息
     */
    @Override
    public UserInfoDto getUserInfoByUser(Long orgId, Long userId, Integer roleType) {
        log.info("*****getUserInfoByUser*******orgId:{},userId:{},roleType:{}",orgId,userId,roleType);
        UserInfoDto userInfoDto = null;
        if (null != orgId) {
            if (roleType == RoleTypeEnum.TEACHER.getValue() || roleType == RoleTypeEnum.EMPLOYEE.getValue()) {
                log.info("*****getUserInfoByUser 查询教师数据*******");
                //查询是否有绑定
                Map<String, Object> employeeParams = new HashMap<String, Object>();
                employeeParams.put("orgId", orgId);
                employeeParams.put("userId", userId);
                EmployeeInfoDto employeeInfo = employeeMapper.getEmployeeInfoByMapParams(employeeParams);
                log.info("*****getUserInfoByUser employeeInfo:{}*******",employeeInfo);
                if (null != employeeInfo) {

                    userInfoDto = new UserInfoDto();
                    userInfoDto.setId(employeeInfo.getUserId());
                    userInfoDto.setOrgId(employeeInfo.getOrgId());
                    userInfoDto.setName(employeeInfo.getName());
                    userInfoDto.setNickName(employeeInfo.getNickName());
                    userInfoDto.setRoleType(roleType);
                    userInfoDto.setUserType(employeeInfo.getUserType()!=null?employeeInfo.getUserType().intValue():null);
                    userInfoDto.setHeadImgUrl(employeeInfo.getHeadImgUrl());
                    userInfoDto.setMobile(employeeInfo.getMobile());
                    userInfoDto.setSex(employeeInfo.getSex());
                    userInfoDto.setProvinceCode(employeeInfo.getProvinceCode());
                    userInfoDto.setProvince(employeeInfo.getProvince());
                    userInfoDto.setCityCode(employeeInfo.getCityCode());
                    userInfoDto.setCity(employeeInfo.getCity());
                    userInfoDto.setAreaCode(employeeInfo.getAreaCode());
                    userInfoDto.setArea(employeeInfo.getArea());
                    userInfoDto.setAddr(employeeInfo.getAddr());
                    userInfoDto.setUserCode(employeeInfo.getUserCode());
                    userInfoDto.setBirthDate(employeeInfo.getBirthDate());
                    userInfoDto.setCardNo(employeeInfo.getCardNo());
                    userInfoDto.setPositionId(employeeInfo.getPositionId());
                    userInfoDto.setPositionName(employeeInfo.getPositionName());
                    userInfoDto.setSmartUserId(employeeInfo.getSmartUserId());
                    userInfoDto.setServiceAreaIds(employeeInfo.getServiceAreaIds());

                    if (null!=employeeInfo.getUserType() && employeeInfo.getUserType().intValue() == UserTypeEnum.TEACHER.getValue()) {
                        //查询班级信息
                        Map<String, Object> classParams = new HashMap<String, Object>();
                        classParams.put("orgId", employeeInfo.getOrgId());
                        classParams.put("masterId", employeeInfo.getUserId());
                        ClassInfo classInfo = classInfoMapper.getByMapParams(classParams);
                        if (null != classInfo) {
                            userInfoDto.setGradeId(classInfo.getGradeId());
                            userInfoDto.setGradeName(classInfo.getGradeName());
                            userInfoDto.setClassId(classInfo.getId());
                            userInfoDto.setClassName(classInfo.getClassName());
                            userInfoDto.setIsClassMaster(true);
                        }
                    }
                }
            } else if (roleType == RoleTypeEnum.FAMILY.getValue()) {
                log.info("*****getUserInfoByUser 查询家长数据*******");
                //查询家长
                Map<String, Object> familyParams = new HashMap<String, Object>();
                familyParams.put("orgId", orgId);
                familyParams.put("userId", userId);
                List<FamilyInfoDto> familyInfoDtoList = familyMapper.getFamilyInfoList(familyParams);
                log.info("*****getUserInfoByUser familyInfoDtoList:{}*******",familyInfoDtoList);
                if (familyInfoDtoList.size() > 0) {
                    FamilyInfoDto familyInfo = familyInfoDtoList.get(0);
                    userInfoDto = new UserInfoDto();
                    userInfoDto.setId(familyInfo.getUserId());
                    userInfoDto.setOrgId(familyInfo.getOrgId());
                    userInfoDto.setName(familyInfo.getName());
                    userInfoDto.setNickName(familyInfo.getNickName());
                    userInfoDto.setHeadImgUrl(familyInfo.getHeadImgUrl());
                    userInfoDto.setMobile(familyInfo.getMobile());
                    userInfoDto.setSex(familyInfo.getSex());
                    userInfoDto.setProvinceCode(familyInfo.getProvinceCode());
                    userInfoDto.setProvince(familyInfo.getProvince());
                    userInfoDto.setCityCode(familyInfo.getCityCode());
                    userInfoDto.setCity(familyInfo.getCity());
                    userInfoDto.setAreaCode(familyInfo.getAreaCode());
                    userInfoDto.setArea(familyInfo.getArea());
                    userInfoDto.setAddr(familyInfo.getAddr());
                    userInfoDto.setRoleType(roleType);
                    userInfoDto.setUserCode(familyInfo.getUserCode());
                    userInfoDto.setBirthDate(familyInfo.getBirthDate());
                    userInfoDto.setCardNo(familyInfo.getCardNo());
                    userInfoDto.setGradeId(familyInfo.getGradeId());
                    userInfoDto.setClassId(familyInfo.getClassId());
                    userInfoDto.setFaceFlag(familyInfo.getFaceFlag());
                    userInfoDto.setSmartUserId(familyInfo.getSmartUserId());
                }
            } else if (roleType == RoleTypeEnum.STUDENT.getValue()) {
                log.info("*****getUserInfoByUser 查询学生数据*******");
                //查询学生
                Map<String, Object> studentParams = new HashMap<String, Object>();
                studentParams.put("orgId", orgId);
                studentParams.put("userId", userId);
                StudentInfoDto studentInfo = studentMapper.getStudentInfoByMapParams(studentParams);
                log.info("*****getUserInfoByUser studentInfo:{}*******",studentInfo);
                if (null != studentInfo) {
                    userInfoDto = new UserInfoDto();
                    userInfoDto.setId(studentInfo.getUserId());
                    userInfoDto.setOrgId(studentInfo.getOrgId());
                    userInfoDto.setName(studentInfo.getName());
                    userInfoDto.setNickName(studentInfo.getNickName());
                    userInfoDto.setHeadImgUrl(studentInfo.getHeadImgUrl());
                    userInfoDto.setSex(studentInfo.getSex());
                    userInfoDto.setProvinceCode(studentInfo.getProvinceCode());
                    userInfoDto.setProvince(studentInfo.getProvince());
                    userInfoDto.setCityCode(studentInfo.getCityCode());
                    userInfoDto.setCity(studentInfo.getCity());
                    userInfoDto.setAreaCode(studentInfo.getAreaCode());
                    userInfoDto.setArea(studentInfo.getArea());
                    userInfoDto.setAddr(studentInfo.getAddr());
                    userInfoDto.setUserCode(studentInfo.getUserCode());
                    userInfoDto.setGradeId(studentInfo.getGradeId());
                    userInfoDto.setGradeName(studentInfo.getGradeName());
                    userInfoDto.setClassId(studentInfo.getClassId());
                    userInfoDto.setClassName(studentInfo.getClassName());
                    userInfoDto.setIsClassMaster(true);
                    userInfoDto.setRoleType(roleType);
                    userInfoDto.setBirthDate(studentInfo.getBirthDate());
                    userInfoDto.setMobile(studentInfo.getMobile());
                    userInfoDto.setStudentNo(studentInfo.getStudentNo());
                    userInfoDto.setSmartUserId(studentInfo.getSmartUserId());
                }
            } else if (roleType == RoleTypeEnum.TOURIST.getValue()) {
                log.info("*****getUserInfoByUser 查询游客数据*******");
                //查询游客
                Map<String, Object> visitorParams = new HashMap<String, Object>();
                visitorParams.put("userId", userId);
                VisitorInfoDto visitorInfo = visitorMapper.getVisitorInfoByMapParams(visitorParams);
                if (null != visitorInfo) {
                    userInfoDto = new UserInfoDto();
                    userInfoDto.setId(visitorInfo.getUserId());
                    userInfoDto.setNickName(visitorInfo.getNickName());
                    userInfoDto.setHeadImgUrl(visitorInfo.getHeadImgUrl());
                    userInfoDto.setRoleType(roleType);
                    userInfoDto.setSex(visitorInfo.getSex());
                    userInfoDto.setProvince(visitorInfo.getProvince());
                    userInfoDto.setCity(visitorInfo.getCity());
                }
            }
        } else {
            log.info("*****getUserInfoByUser 查询游客数据*******");
            if (roleType == RoleTypeEnum.TOURIST.getValue()) {
                //查询游客
                Map<String, Object> visitorParams = new HashMap<String, Object>();
                visitorParams.put("userId", userId);
                VisitorInfoDto visitorInfo = visitorMapper.getVisitorInfoByMapParams(visitorParams);
                if (null != visitorInfo) {
                    userInfoDto = new UserInfoDto();
                    userInfoDto.setId(visitorInfo.getUserId());
                    userInfoDto.setNickName(visitorInfo.getNickName());
                    userInfoDto.setHeadImgUrl(visitorInfo.getHeadImgUrl());
                    userInfoDto.setRoleType(roleType);
                    userInfoDto.setSex(visitorInfo.getSex());
                    userInfoDto.setProvince(visitorInfo.getProvince());
                    userInfoDto.setCity(visitorInfo.getCity());
                }
            }
        }
        return userInfoDto;
    }

    @Override
    public UserOpen getUserOpenByUser(Map<String, Object> params) {
        return userOpenMapper.getByMapParams(params);
    }

    @Override
    public void addUserLoginLog(UserLoginLog userLoginLog) {
        userLoginLogMapper.insert(userLoginLog);
    }

    @Override
    public UserLastLogin getUserLastLogin(Map<String, Object> params)
    {
        return userLastLoginMapper.getUserLastLogin(params);
    }

    @Override
    public void addUserLastLogin(UserLastLogin userLastLogin) {
        userLastLoginMapper.insert(userLastLogin);
    }

    @Override
    public void updateUserLastLogin(UserLastLogin userLastLogin) {
        userLastLoginMapper.update(userLastLogin);
    }

    @Override
    public void updateUserLastLoginStatus(Map<String, Object> params)
    {
        userLastLoginMapper.updateUserLastLoginStatus(params);
    }

    @Override
    public User getNewUserByOld(Long orgId, Integer roleType, Long oldUserId) {
        User user = null;
        Long userId = null;
        if (roleType == RoleTypeEnum.TEACHER.getValue()) {
            Map<String, Object> employeeParams = new HashMap<String, Object>();
            employeeParams.put("orgId", orgId);
            employeeParams.put("oldUserId", oldUserId);
            Employee employee = employeeMapper.getByMapParams(employeeParams);
            if (null != employee) {
                userId = employee.getUserId();
            }
        } else if (roleType == RoleTypeEnum.FAMILY.getValue()) {
            Map<String, Object> familyParams = new HashMap<String, Object>();
            familyParams.put("orgId", orgId);
            familyParams.put("oldUserId", oldUserId);
            Family family = familyMapper.getByMapParams(familyParams);
            if (null != family) {
                userId = family.getUserId();
            }
        } else if (roleType == RoleTypeEnum.STUDENT.getValue()) {
            Map<String, Object> studentParams = new HashMap<String, Object>();
            studentParams.put("orgId", orgId);
            studentParams.put("oldUserId", oldUserId);
            Student student = studentMapper.getByMapParams(studentParams);
            if (null != student) {
                userId = student.getUserId();
            }
        }

        if (null != userId) {
            user = userMapper.getByPrimaryKey(userId);
        }

        return user;
    }

    /**
     * 检查卡号
     *
     * @param cardNo
     * @param orgId
     * @return
     */
    @Override
    public Boolean checkCardNo(String cardNo, Long orgId) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("orgId", orgId);
        params.put("cardNo", cardNo);

        if (studentMapper.getCountByCardNo(params) > 0) {
            return true;
        }

        return false;
    }

    /**
     * 检测卡号是否存在
     * @param cardNo 卡号
     * @param orgId 学校
     * @param userList 已存在用户
     * @return 是否存在
     */
    @Override
    public Boolean checkCardNo(String cardNo, Long orgId, List<Long> userList){
        Map<String, Object> params = new HashMap<>(3);
        params.put("orgId", orgId);
        params.put("cardNo", cardNo);
        params.put("userList", CollectionUtils.isEmpty(userList) ? null : userList);
        return studentMapper.getCountByCardNo(params) > 0;
    }

    /**
     * 判断手机号在系统中唯一
     * @param orgId
     * @param mobile
     * @return
     */
    @Override
    public UserInfoDto checkMobileUnique(Long orgId, String mobile,Integer roleType) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orgId", orgId);
        params.put("mobile", mobile);
        params.put("roleType", roleType);
        return userMapper.getUserInfoByMobile(params);
    }

    /**
     * 判断手机号在系统中唯一
     * @param mobile
     * @return
     */
    @Override
    public User checkUserMobile(String mobile) {
        Map<String, Object> params = new HashMap<String, Object>(1);
        params.put("mobile", mobile);
        User user = userMapper.getByMapParams(params);
        return user;
    }

    /**
     * //分别查询老师,家长,学生表来判断考勤卡号唯一
     * @param cardNo
     * @return
     */
    @Override
    public Boolean checkCardNoUnique(String cardNo,Long orgId){
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("cardNo",cardNo);
        paramMap.put("orgId",orgId);
        List<Employee> employeeList = employeeMapper.getListByMapParams(paramMap);
        if(!CollectionUtils.isEmpty(employeeList)){
            return true;
        }
        List<Student> studentList = studentMapper.getListByMapParams(paramMap);
        if(!CollectionUtils.isEmpty(studentList)){
            return true;
        }
        List<Family> familyList = familyMapper.getListByMapParams(paramMap);
        if(!CollectionUtils.isEmpty(familyList)){
            return true;
        }
        return false;
    }
	
	@Override
    @Transactional
    public void deleteUserData(Long orgId) {
        //1、先查询出全部学生,老师,家长
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("orgId",orgId);
        List<Employee> employeeList = employeeMapper.getListByMapParams(paramMap);
        List<Student> studentList = studentMapper.getListByMapParams(paramMap);
        List<Family> familyList = familyMapper.getListByMapParams(paramMap);
        //2、正式用户(老师,学生,家长)变成游客
        if(!CollectionUtils.isEmpty(employeeList)){
            for(Employee employee:employeeList){
                //先查询user
                User user = userMapper.getByPrimaryKey(employee.getUserId());
                Object roleType = updateRoleTypeJson(user.getRoleType(), (short) RoleTypeEnum.TEACHER.getValue(), null, orgId, null,user.getId());
                user.setRoleType(roleType);
                userMapper.update(user);
            }
        }
        if(!CollectionUtils.isEmpty(studentList)){
            for (Student student : studentList) {
                //先查询user
                User user = userMapper.getByPrimaryKey(student.getUserId());
                Object roleType = updateRoleTypeJson(user.getRoleType(), (short)RoleTypeEnum.STUDENT.getValue(), null, orgId, null,user.getId());
                user.setRoleType(roleType);
                userMapper.update(user);
            }
        }
        if(!CollectionUtils.isEmpty(familyList)){
            for (Family family : familyList) {
                //先查询user
                User user = userMapper.getByPrimaryKey(family.getUserId());
                Object roleType = updateRoleTypeJson(user.getRoleType(), (short)RoleTypeEnum.FAMILY.getValue(), null, orgId, null,user.getId());
                user.setRoleType(roleType);
                userMapper.update(user);
            }
        }
        //3、清除全部正式用户(老师,学生,家长)数据
        userMapper.deleteUserData(orgId);
    }

    @Override
    public Integer getUserCount(UserStatRoleTypeEnum userStatRoleType, Long orgId, Long gradeId, Long classId)
    {
        Integer count = 0;

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("orgId",orgId);
        paramMap.put("gradeId",gradeId);
        paramMap.put("classId",classId);

        if(userStatRoleType == UserStatRoleTypeEnum.TEACHER){
            count = employeeMapper.getEmployeeCount(paramMap);
        }
        else if(userStatRoleType == UserStatRoleTypeEnum.FAMILY){
            count = familyMapper.getFamilyCount(paramMap);
        }
        else if(userStatRoleType == UserStatRoleTypeEnum.STUDENT){
            count = studentMapper.getStudentCount(paramMap);
        }
        else if(userStatRoleType == UserStatRoleTypeEnum.CLASS)
        {
            int familyCount = familyMapper.getFamilyCount(paramMap);
            int studentCount = studentMapper.getStudentCount(paramMap);
            count = familyCount + studentCount;
        }
        else if(userStatRoleType == UserStatRoleTypeEnum.SCHOOL)
        {
            int employeeCount = employeeMapper.getEmployeeCount(paramMap);
            int studentCount = studentMapper.getStudentCount(paramMap);
            count = employeeCount + studentCount;
        }
        else if(userStatRoleType == UserStatRoleTypeEnum.ALL)
        {
            int employeeCount = employeeMapper.getEmployeeCount(paramMap);
            int studentCount = studentMapper.getStudentCount(paramMap);
            int familyCount = familyMapper.getFamilyCount(paramMap);
            count = employeeCount + studentCount + familyCount;
        }
        return count;
    }


    @Override
    public void deleteRedisWkbbBasicUserBack(Long userId,Long orgId) {
        log.info("********BaseController.deleteRedisWkbbBasicUserBack********userId:{},orgId:{}", userId, orgId);

        log.info("----------开始清除前端用户缓存----------", userId, orgId);
       /* ResultDTO<AccountDto> resultDTO = wxFeignService.getAccountByOrg(orgId);
        if (resultDTO.isSuccess()) {
            AccountDto account = resultDTO.getData();

            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userId", userId);
            params.put("accountId", account.getId());

            List<UserUnion> userUnionList = userUnionMapper.getListByMapParams(params);
            log.info("*******deleteRedisWkbbBasicUserBack******userUnionList:{}", userUnionList.size());
            for (UserUnion union : userUnionList) {
                if (!StringUtils.isEmpty(union.getUnionId())) {
                    //清除3.0用户缓存
                    String userTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_FRONT + RedisKeyConstant.WKBB_BASIC_USER_FRONT_ACCOUNT_UNIONID, union.getAccountId(), union.getUnionId());
                    if (!StringUtil.isEmpty(userTokenRedisKey)) {
                        redisTemplateUtil.delete(userTokenRedisKey);
                    }

                    //清除路由用户缓存
                    String userRouteTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_ROUTE + RedisKeyConstant.WKBB_BASIC_USER_ROUTE_TOKEN_UNIONID, union.getUnionId());
                    if (!StringUtil.isEmpty(userRouteTokenRedisKey)) {
                        redisTemplateUtil.delete(userRouteTokenRedisKey);
                    }
                }
            }
        }*/

        log.info("----------除前端用户缓存完成----------",userId,orgId);
    }

    @Override
    @Transactional
    public boolean clearBindUser(Long orgId,String mobile)
    {
        try {
            log.info("********清除用户绑定关系*******orgId:{} mobile:{}", orgId, mobile);
            //查询用户是否存在
            User user = userOpenService.getUserExistOrg(orgId, mobile);
            if (null == user) {
                return false;
            }

          /*  ResultDTO<AccountDto> resultDTO = wxFeignService.getAccountByOrg(orgId);
            if (resultDTO.isSuccess()) {
                AccountDto account = resultDTO.getData();

                if (null != account) {
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("userId", user.getId());
                    params.put("accountId", account.getId());

                    List<UserUnion> userUnionList = userUnionMapper.getListByMapParams(params);
                    log.info("*******clearBindUser******用户{}是否绑定:{}", user.getId(), userUnionList.size() > 0 ? "已绑定" : "未绑定");

                    if (userUnionList.size() > 0) {
                        //清除绑定关系
                        UserOpen userOpen = new UserOpen();
                        userOpen.setAccountId(account.getId());
                        userOpen.setUserId(user.getId());
                        userOpenMapper.delete(userOpen);

                        UserUnion userUnion = new UserUnion();
                        userUnion.setAccountId(account.getId());
                        userUnion.setUserId(user.getId());
                        userUnionMapper.delete(userUnion);

                        UserLastLogin userLastLogin = new UserLastLogin();
                        userLastLogin.setAccountId(account.getId());
                        userLastLogin.setOrgId(orgId);
                        userLastLogin.setUserId(user.getId());
                        userLastLoginMapper.delete(userLastLogin);

                        //最后清redis
                        for (UserUnion union : userUnionList) {
                            if (!StringUtils.isEmpty(union.getUnionId())) {
                                String userTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_FRONT + RedisKeyConstant.WKBB_BASIC_USER_FRONT_ACCOUNT_UNIONID, union.getAccountId(), union.getUnionId());
                                log.info("********clearBindUser********userJsonStr:{}", userTokenRedisKey);
                                if (!StringUtil.isEmpty(userTokenRedisKey)) {
                                    redisTemplateUtil.delete(userTokenRedisKey);
                                }

                                //清除路由用户缓存
                                String userRouteTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_ROUTE + RedisKeyConstant.WKBB_BASIC_USER_ROUTE_TOKEN_UNIONID, union.getUnionId());
                                if (!StringUtil.isEmpty(userRouteTokenRedisKey)) {
                                    redisTemplateUtil.delete(userRouteTokenRedisKey);
                                }
                            }
                        }
                    }
                }
            }*/
        }
        catch (Exception e)
        {
            log.error("*****清除用户绑定关系异常******",e);
        }

        return true;
    }

    @Override
    public boolean clearBindUserByAccount(Long accountId,String unionId)
    {
        try {
            //清除绑定关系
            UserOpen userOpen = new UserOpen();
            userOpen.setAccountId(accountId);
            userOpen.setUnionId(unionId);
            userOpenMapper.delete(userOpen);

            UserUnion userUnion = new UserUnion();
            userUnion.setAccountId(accountId);
            userUnion.setUnionId(unionId);
            userUnionMapper.delete(userUnion);
        }
        catch (Exception e)
        {
            log.error("*****清除用户绑定关系异常******",e);
        }

        return true;
    }

    @Override
    public boolean clearBindUserByMobile(String mobile)
    {
        try {
            log.info("********根据手机号清除用户绑定关系*******mobile:{}", mobile);
            //查询用户是否存在
            User user = this.getUserByMobile(mobile);
            if (null == user) {
                return false;
            }

            String roleTypeJsonStr = JSON.toJSONString(user.getRoleType());

            log.info("*************clearBindUserByMobile****************roleTypeJsonStr:{}", roleTypeJsonStr);
            List<RoleTypeJsonDto> roleTypeJsonDtoList = JSONObject.parseArray(roleTypeJsonStr, RoleTypeJsonDto.class);
            for (RoleTypeJsonDto roleTypeJsonDto : roleTypeJsonDtoList) {
                if (null != roleTypeJsonDto.getOrgId()) {
                    Long orgId = roleTypeJsonDto.getOrgId();
                    this.clearBindUser(orgId, mobile);
                }
            }
        }
        catch (Exception e)
        {
            log.error("*****清除用户绑定关系异常******",e);
        }

        return true;
    }

    @Override
    public void clearOrgBindUser(Long orgId)
    {
        log.info("********清除学校用户绑定关系开始*******orgId:{}",orgId);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orgId", orgId);

        //查询老师
        List<Employee> employeeList = employeeMapper.getAllUserListByMapParams(params);
        int employeeTotal = employeeList.size();
        log.info("学校{}存在老师数量：{}",orgId,employeeTotal);

        //查询家长
        List<Family> familyList = familyMapper.getAllUserListByMapParams(params);
        int familyTotal = familyList.size();
        log.info("学校{}存在家长数量：{}",orgId,familyTotal);

        int employeeCount = 0;
        for(Employee employee : employeeList)
        {
            log.info("老师用户数量:{} 剩余待解绑数量：{}",employeeTotal,employeeTotal-employeeCount++);
            if(!StringUtils.isEmpty(employee.getMobile())) {
                this.clearBindUser(orgId, employee.getMobile());
            }
        }

        int familyCount = 0;
        for(Family family : familyList)
        {
            log.info("家长用户数量:{} 剩余待解绑数量：{}",familyTotal,familyTotal-familyCount++);
            if(!StringUtils.isEmpty(family.getMobile())) {
                this.clearBindUser(orgId, family.getMobile());
            }
        }

        log.info("********清除学校用户绑定关系结束*******");
    }

    /**
     * 清除用户登录缓存
     * */
    @Override
    public void clearUserLoginRedis(Boolean routeFlag,Long orgId,Long userId,String unionId)
    {
        List<UserUnion> unionList = new ArrayList<>();
        /*ResultDTO<AccountDto> resultDto = wxFeignService.getAccountByOrg(orgId);
        if (null != resultDto && resultDto.isSuccess() && null != resultDto.getData()) {

            Long accountId = resultDto.getData().getId();
            if(null==userId && StringUtil.isEmpty(unionId)) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("orgId", orgId);

                //查询老师
                List<Employee> employeeList = employeeMapper.getAllUserListByMapParams(params);
                int employeeTotal = employeeList.size();
                log.info("学校{}存在老师数量：{}",orgId,employeeTotal);

                //查询家长
                List<Family> familyList = familyMapper.getAllUserListByMapParams(params);
                int familyTotal = familyList.size();
                log.info("学校{}存在家长数量：{}",orgId,familyTotal);

                int employeeCount = 0;
                for(Employee employee : employeeList)
                {
                    Map<String, Object> unionParams = new HashMap<>();
                    unionParams.put("accountId", accountId);
                    unionParams.put("userId", employee.getUserId());

                    List<UserUnion> userUnionList = userUnionMapper.getListByMapParams(unionParams);
                    unionList.addAll(userUnionList);
                }

                int familyCount = 0;
                for(Family family : familyList)
                {
                    Map<String, Object> unionParams = new HashMap<>();
                    unionParams.put("accountId", accountId);
                    unionParams.put("userId", family.getUserId());

                    List<UserUnion> userUnionList = userUnionMapper.getListByMapParams(unionParams);
                    unionList.addAll(userUnionList);
                }
            }
            else
            {
                Map<String, Object> params = new HashMap<>();
                params.put("accountId", accountId);
                params.put("userId", userId);
                params.put("unionId", unionId);

                unionList = userUnionMapper.getListByMapParams(params);
            }
        }*/

        //清除redis
        for(UserUnion union : unionList){
            if (!StringUtils.isEmpty(union.getUnionId())) {
                String userTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_FRONT + RedisKeyConstant.WKBB_BASIC_USER_FRONT_ACCOUNT_UNIONID, union.getAccountId(), union.getUnionId());
                if (!StringUtil.isEmpty(userTokenRedisKey)) {
                    redisTemplateUtil.delete(userTokenRedisKey);
                }

                //清除路由用户缓存
                if(routeFlag) {
                    String userRouteTokenRedisKey = String.format(RedisKeyConstant.WKBB_BASIC_USER_ROUTE + RedisKeyConstant.WKBB_BASIC_USER_ROUTE_TOKEN_UNIONID, union.getUnionId());
                    if (!StringUtil.isEmpty(userRouteTokenRedisKey)) {
                        redisTemplateUtil.delete(userRouteTokenRedisKey);
                    }
                }
            }
        }
    }

    /**
     * 获取图片md5值
     */
    @Override
    public String getImageMD5(String url){
        String key = RedisKeyConstant.WKBB_BASIC_IMAGE_MD5+NewMD5Util.getStringMD5(url);
        Object value = redisTemplateUtil.get(key);
        if(null != value){
            return value.toString();
        }else {
            String md5 = NewMD5Util.getMD5(url);
            redisTemplateUtil.set(key,RedisKeyConstant.EXPIRATION_TIME_1_MONTH);
            return md5;
        }
    }

    @Override
    @Transactional(readOnly=true)
    public PageInfo<UserDto> getAppletUserPageList(HashMap<String, Object> params, Integer pageNo, Integer pageSize) {
        Page<UserDto> page = PageHelper.startPage(pageNo, pageSize, true);
        PageInfo<UserDto> pageInfo = new PageInfo<>(userMapper.getAppletUserPageList(params));
        pageInfo.setTotal(page.getTotal());
        return pageInfo;
    }

}
